﻿using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;

// ReSharper disable once CheckNamespace
// 限定名称空间以减少引用

namespace System
{
    /// <summary>
    /// 针对字符串类型的扩展类
    /// </summary>
    public static class StringExtension
    {
        /// <summary>
        /// 判断该字符串是否为空或者是否为空引用
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsNullOrWhiteSpace(this string source)
        {
            return string.IsNullOrWhiteSpace(source);
        }

        /// <summary>
        /// 字符串分割扩展，可以使用字符串作为分隔符
        /// </summary>
        /// <param name="source"></param>
        /// <param name="splitor"></param>
        /// <param name="comparison"></param>
        /// <returns></returns>
        public static IEnumerable<string> Split(this string source, string splitor,
            StringComparison comparison = StringComparison.Ordinal)
        {
            while (source.Contains(splitor))
            {
                var index = source.IndexOf(splitor, comparison);
                yield return source.Substring(0, index);
                source = source.Substring(index + splitor.Length);
            }
            yield return source;
        }

        /// <summary>
        /// 移除UTF8编码开始的空白之后，进行Trim
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string TrimWithBom(this string source)
        {
            var byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
            if (/*source.StartsWith(byteOrderMarkUtf8) &&*/ source[0] == 65279)
            {
                source = source.Remove(0, byteOrderMarkUtf8.Length);
            }
            return source.Trim();
        }

        /// <summary>
        /// 由一个字符转型为Guid
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Guid? Guid(this string str)
        {
            Guid guid;
            return System.Guid.TryParse(str, out guid) ? guid : default(Guid?);
        }
    }
}